import os
import re
from collections import defaultdict

def allowed_file(filename, allowed_extensions):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in allowed_extensions

def extract_hot_pixels_from_txt(txt_path):
    hot_pixels = []
    timestamp_match = re.search(r'T(\d{8})', txt_path)
    timestamp = timestamp_match.group(1) if timestamp_match else "unknown"
    file_id = os.path.basename(txt_path)
    with open(txt_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    data_section = False
    for line in lines:
        if re.match(r'\s*\d+\s+\d+\s+\d+', line):
            data_section = True
        if data_section:
            parts = line.strip().split()
            if len(parts) >= 9:
                x = int(parts[1])
                y = int(parts[2])
                orig_val = float(parts[3])
                local_mean = float(parts[6])
                hot_pixels.append((x, y, timestamp, orig_val, local_mean, file_id))
    return hot_pixels

def build_global_index(txt_files, tolerance=0):
    global_index = defaultdict(list)
    for txt_file in txt_files:
        hot_pixels = extract_hot_pixels_from_txt(txt_file)
        for x, y, timestamp, orig_val, local_mean, file_id in hot_pixels:
            matched = False
            for dx in range(-tolerance, tolerance + 1):
                for dy in range(-tolerance, tolerance + 1):
                    key = (x + dx, y + dy)
                    if key in global_index:
                        matched = True
                        global_index[key].append((timestamp, dx, dy, orig_val, local_mean, file_id))
                        break
                if matched:
                    break
            if not matched:
                global_index[(x, y)].append((timestamp, 0, 0, orig_val, local_mean, file_id))
    return global_index

def generate_report_content(global_index, total_files, tolerance, threshold):
    content = []
    content.append("全局热像素索引匹配结果")
    content.append("=" * 60)
    content.append(f"坐标误差容忍: ±{tolerance} 像素")
    content.append(f"匹配成功阈值 P: {threshold:.2f}")
    content.append(f"候选热像素总数: {len(global_index)}")
    
    num_successful = sum(1 for values in global_index.values() 
                       if len(set(v[5] for v in values)) / total_files >= threshold)
    global_rate = num_successful / len(global_index) if len(global_index) > 0 else 0
    
    content.append(f"匹配成功热像素数: {num_successful}")
    content.append(f"整体识别率: {global_rate:.2f}\n")
    content.append("字段说明:\n  timestamp, x_bias, y_bias, orig_val, local_mean")
    content.append("=" * 60 + "\n")

    for idx, (key, values) in enumerate(global_index.items(), start=1):
        file_ids = set(v[5] for v in values)
        match_rate = len(file_ids) / total_files
        content.append(f"[{idx}] 坐标: {key} 匹配文件数: {len(file_ids)} / {total_files} 识别率: {match_rate:.2f}")
        for v in values:
            content.append(f"    {v[0]}, {v[1]}, {v[2]}, {v[3]}, {v[4]}")
        content.append("-" * 40)
    
    return "\n".join(content)